import socket
import struct

def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('0.0.0.0', 4321))
    server_socket.listen(1)
    print("Server listening on port 4321...")
    
    while True:
        client_socket, addr = server_socket.accept()
        print(f"Accepted connection from {addr}")
        
        try:
            # 接收ping
            data = client_socket.recv(4)
            if data.decode() == 'ping':
                client_socket.sendall(b'pong')
                print("Received ping, sent pong")
                
                # 接收文件名长度 (4字节)
                filename_len_data = client_socket.recv(4)
                filename_len = struct.unpack('!I', filename_len_data)[0]
                
                # 接收文件名
                filename = client_socket.recv(filename_len).decode('utf-8')
                print(f"Receiving file: {filename}")
                
                # 接收文件长度 (4字节)
                file_len_data = client_socket.recv(4)
                file_len = struct.unpack('!I', file_len_data)[0]
                
                # 接收文件数据
                file_data = b''
                while len(file_data) < file_len:
                    chunk = client_socket.recv(file_len - len(file_data))
                    if not chunk:
                        raise Exception("Connection closed prematurely")
                    file_data += chunk
                
                # 保存文件
                with open(filename, 'wb') as f:
                    f.write(file_data)
                print(f"File saved: {filename} ({file_len} bytes)")
                
            else:
                print(f"Received unknown data: {data}")
                
        except Exception as e:
            print(f"Error handling client: {e}")
        finally:
            client_socket.close()

if __name__ == "__main__":
    main()